<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 岗位管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                        type="primary"
                        icon="el-icon-delete"
                        class="handle-del mr10"
                        @click="delAllSelection"
                >批量删除</el-button>
                <el-input v-model="query.id" placeholder="版块编号" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-lx-add" @click="handleAdd()">新建</el-button>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="sectionName" label="岗位名称"></el-table-column>
                <el-table-column prop="notice" label="公告"></el-table-column>
<!--                <el-table-column prop="userId.username" label="所属用户"></el-table-column>-->
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-lx-attention"
                                @click="handleSelect(scope.$index, scope.row)"
                        >查询</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
<!--                <el-pagination-->
<!--                        background-->
<!--                        layout="prev, pager, next"-->
<!--                        :current-page="currentPage"-->
<!--                        :page-size="pageSize"-->
<!--                        :total="total"-->
<!--                        @current-change="getData"-->
<!--                ></el-pagination>-->
                <el-pagination
                        background
                        layout="prev, pager, next"
                        :current-page="currentPage"
                        :page-size="pageSize"
                        :total="total"
                        @current-change="getData"
                ></el-pagination>
            </div>

        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form
                    ref="form"
                    :model="form"
                    label-width="80px"
                    :rules="rules2"
                    class="demo-ruleForm"
            >
                <el-form-item label="岗位 ID">
                    <el-input v-model="form.id" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="版块名称" prop="sectionName">
                    <el-input v-model="form.sectionName"></el-input>
                </el-form-item>
                <el-form-item label="公告" prop="notice">
                    <el-input v-model="form.notice"></el-input>
                </el-form-item>
                <el-form-item label="所属ID" prop="userId">
                    <el-input v-model="form.userId"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
            </span>
        </el-dialog>

        <!--新建弹出框-->
        <el-dialog title="新建" :visible.sync="addVisible" width="50%">
            <el-form
                    ref="add"
                    :model="add"
                    label-width="80px"
                    :rules="rules2"
                    class="demo-ruleForm"
            >
                <el-form-item label="版块名称" prop="sectionName">
                    <el-input v-model="add.sectionName"></el-input>
                </el-form-item>
                <el-form-item label="公告" prop="notice">
                    <el-input v-model="add.notice"></el-input>
                </el-form-item>
                <el-form-item label="所属用户ID" prop="num">
                    <el-input v-model="add.userId"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd('add')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    //导入Stat对应的api

    import { deleteStatById } from '../../api/apis/stat';
    import { addStat } from '../../api/apis/stat';
    import { sectionlist } from '../../network/sectionmanage';
    import { sectionview } from '../../network/sectionmanage';
    import { savesection } from '../../network/sectionmanage';
    import { sectiondelete } from '../../network/sectionmanage';

    //这里要引入表单验证规则
    import valrule from '../../config/validaterule';
    import { search } from '../../network/fuzzysearch';
    import { getPostById } from '../../network/post';

    export default {
        name: 'stat',
        data() {
            return {
                // 新建岗位表单校验
                rules: {
                    name: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
                    type: [{ required: true, message: '请输入岗位类型', trigger: 'blur' }],
                    num: [{ required: true, trigger: 'blur', validator: valrule.validInteger }]
                },
                //编辑部门表单校验
                rules2: {
                    sectionName: [{ required: true, message: '请输入版块名称', trigger: 'blur' }],
                    notice: [{ required: true, message: '公告', trigger: 'blur' }],
                    username: [{ required: true, trigger: 'blur', /*validator: valrule.validInteger*/ }]
                },
                //查询的相关参数
                query: {
                    id: '', //岗位id
                    name: '', //岗位名称
                    pageIndex: 1, //当前请求页
                    pageSize: 5 //一页显示的数据条数
                },
                //添加的相关参数
                add: {
                    sectionName: '', //岗位名称
                    notice: '', //岗位编制
                    userId: '' //岗位类型
                },
                tableData: [], //获取的数据
                multipleSelection: [],
                delList: [],
                editVisible: false, //编辑弹出框false隐藏，true显示
                addVisible: false, //新建弹出框false隐藏，true显示

                total:0,
                pageSize:10,
                currentPage:1,
                form: {},
                idx: -1,
                id: -1
            };
        },
        created() {
            this.getData(1);
        },
        methods: {
            //时间格式化
            dateFormat(row, column) {
                var dT = new Date(row.createTime); //row 表示一行数据, dateTime 表示要格式化的字段名称
                return dT.getFullYear() + '-' + (dT.getMonth() + 1) + '-' + dT.getDate();
            },
            //query表单参数判空,如果参数为空字符串或null等则不发送请求
            queryIsNull() {
                let queryForm = {
                    // id: this.query.id, //部门id
                    // name: this.query.name, //部门名称
                    pageIndex: this.query.pageIndex, //当前请求页
                    pageSize: this.query.pageSize //一页显示的数据条数
                };

                if (this.query.id.split(' ').join('').length !== 0 && this.query.id !== null && this.query.id !== undefined) {
                    //alert('id不为空');
                    queryForm.id = this.query.id;
                } else {
                    //alert('id为空');
                }

                if (this.query.name.split(' ').join('').length !== 0 && this.query.name !== null && this.query.name !== undefined) {
                    //alert('id不为空');
                    queryForm.name = this.query.name;
                } else {
                    //alert('name为空');
                }

                return queryForm;
            },

            //初始化数据
            getData(currentPage) {
                // let queryForm = this.queryIsNull();
                // console.log('表单');
                // console.log(queryForm);
                const _this = this;

                sectionlist(currentPage)
                    .then((res) => {
                        console.log(res);
                        if (res.code === 200) {
                            console.log(res);
                            _this.currentPage = res.data.current;
                            _this.pageSize = res.data.size;
                            _this.total = res.data.total;
                            _this.tableData = res.data.records;
                            console.log("size:"+res.data.size);
                            console.log("total:"+res.data.total);
                            console.log("current:"+res.data.current);
                        } else {
                            this.$message.error('数据获取失败，' + res.msg);
                        }
                    })
                    .catch(() => {
                        this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址或参数是否正确');
                    });
            },
            // 新建操作
            handleAdd() {
                //alert("即将进入新建页面")
                this.addVisible = true;
            },
            // 保存新建
            saveAdd(add) {
                console.log('添加');
                console.log(this.add);
                this.$refs[add].validate((valid) => {
                    if (valid) {
                        this.addVisible = false;
                        savesection(this.add)
                            .then((res) => {
                                console.log(res);
                                if (res.code === 200) {
                                    this.$message.success('新建岗位成功');
                                    this.getData();
                                } else {
                                    this.$message.error('新建岗位失败');
                                    this.getData();
                                }
                                this.addVisible = false;
                            })
                            .catch(() => {
                                this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址是否正确');
                            });
                    } else {
                        this.$message.error('请按照指定格式输入');
                        return false;
                    }
                });
            },
            // 编辑操作
            handleEdit(index, row) {
                //alert("即将进入编辑页面")
                this.idx = index;
                this.form = row;
                this.editVisible = true;
            },
            // 保存编辑
            saveEdit(form) {
                console.log('编辑');
                console.log(this.form);
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        savesection(this.form)
                            .then((res) => {
                                console.log(res);

                                if (res.code === 200) {
                                    //表示更新成功
                                    this.editVisible = false;
                                    this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                                    this.$set(this.tableData, this.idx, this.form);
                                    this.getData();
                                } else {
                                    //表示更新失败
                                    this.editVisible = false;
                                    this.$message.error(`修改第 ${this.idx + 1} 行失败`);
                                    this.getData();
                                }
                            })
                            .catch(() => {
                                this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址是否正确');
                            });
                    } else {
                        this.$message.error('请按照指定格式输入');
                        return false;
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                // this.getData();
                if(this.query.id==''){
                    this.getData();
                }else {
                    // alert(this.query.id);
                    sectionview(this.query.id)
                        .then((res) => {
                            if (res.code === 200) {
                                console.log(res);
                                this.tableData = []
                                let info = {
                                    id: res.data.id,
                                    sectionName: res.data.sectionName,
                                    notice: res.data.notice,
                                    // userId:res.data.userId,

                                }
                                this.tableData.push(info)
                                this.size = 1;
                                this.current = 1;
                                this.total = 1;
                            } else {
                                this.$message.error('数据获取失败，' + res.msg);
                            }
                        })
                        .catch(() => {
                            this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址或参数是否正确');
                        });
                }
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    sectiondelete({ id: row.id }).then((res) => {
                        console.log(res);
                        if (res.code === 200) {
                            this.$message.success('删除成功');
                            //this.tableData.splice(index, 1);
                            this.getData();
                        } else {
                            this.$message.error('删除失败');
                            this.getData();
                        }
                    });
                });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            delAllSelection() {
                const length = this.multipleSelection.length;
                this.delList = this.delList.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    let str = this.multipleSelection[i].name;
                    sectiondelete({ id: this.multipleSelection[i].id })
                        .then((res) => {
                            console.log(res);
                            if (res.code === 200) {
                                this.$message.success('删除' + str + '成功');
                            } else {
                                this.$message.success('删除' + str + '失败');
                            }
                        })
                        .catch(() => {
                            this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址是否正确');
                        });
                }
                this.getData();
                this.multipleSelection = [];
            },
            // 查询操作
            handleSelect(index, row) {
                alert('查询操作');
            },
            // 分页导航
            handlePageChange(val) {
                alert('请求的页数：' + val);

                // 调用方法：this.$set( target, key, value )
                // target：要更改的数据源(可以是对象或者数组)
                // key：要更改的具体数据
                // value ：重新赋的值
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
</style>
